package com.collins.io.nio.discard;

import com.collins.io.nio.config.Config;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

public class DiscardServer {
    private static final Logger logger = Logger.getLogger(DiscardServer.class);
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) throws IOException {
        startServer();
    }

    public static void startServer() throws IOException {
        // TODO 1 gain selector
        Selector selector = Selector.open();
        // TODO 2 gain server socket channel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(Config.SERVER_PORT));
        logger.info(sdf.format(new Date(System.currentTimeMillis())) + " sever listening on port 8081...");
        // TODO 3 register ACCEPT to selector
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (selector.select() > 0) {
            // TODO 4 gain selector iterator
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                // TODO 5 gain single SelectionKey
                SelectionKey key = iterator.next();
                if(key.isAcceptable()) {
                    SocketChannel channel = serverSocketChannel.accept();
                    channel.configureBlocking(false);
                    channel.register(selector, SelectionKey.OP_READ);
                }else if(key.isReadable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(Config.SERVER_BUFFER_SIZE);
                    int len = 0;
                    while((len = channel.read(buffer)) > 0) {
                        buffer.flip();
                        logger.info(sdf.format(new Date(System.currentTimeMillis())) +
                                " received[" + len + "] " + new String(buffer.array(), 0, len) );
                        buffer.clear();
                    }
                    channel.close();
                }
                // TODO 6 remove used keys
                iterator.remove();
            }
        }
        serverSocketChannel.close();
    }
}
